//
//  MineView.swift
//  MineView
//
//  Created by Ben on 2021/8/13.
//

import SwiftUI
import SDWebImage


@MainActor
struct MineView: View {
    @EnvironmentObject var customTabbarVM: CustomTabbarViewModel
    //    @State var pass: String = ""
    @EnvironmentObject var initVM: InitViewModel
    
    @State var headerViewMinY: CGFloat = 0
    @State var scrollViewOffsetY: CGFloat = 0
    // nav透明度
    @State var navViewAlpha: CGFloat = 0
    // 这里是事先准备好的模型数据，用来展现我的页面的按钮
    private var mineUserTools: [MineToolModel] = [
        MineToolModel(
            title: "我的交易",
            itemList: [
                MineToolItemModel(title: "我发布的", icon: "mine_bag", value: 19),
                MineToolItemModel(title: "我卖出的", icon: "mine_saled", value: 3),
                MineToolItemModel(title: "我买到的", icon: "mine_history", value: 129),
                MineToolItemModel(title: "我可转卖的", icon: "mine_taobao", value: nil),
            ]),
        MineToolModel(
            title: "我的会玩",
            itemList: [
                MineToolItemModel(title: "我的圈子", icon: "mine_message", value: nil),
                MineToolItemModel(title: "我的帖子", icon: "mine_blog", value: nil),
                MineToolItemModel(title: "创作者中心", icon: "mine_author_center", value: nil),
                MineToolItemModel(title: "创作学院", icon: "mine_author_school", value: nil),
            ]),
        MineToolModel(
            title: "互动权益",
            itemList: [
                MineToolItemModel(title: "领闲鱼币", icon: "home_signIn", value: nil),
                MineToolItemModel(title: "闲鱼连连消", icon: "mine_game", value: nil),
                MineToolItemModel(title: "闲鱼农场", icon: "mine_farm", value: nil),
            ]),
        
    ]
    
    private var mineSystemTools: [MineToolItemModel] = [
        MineToolItemModel(title: "咸鱼公约", icon: "mine_system_global_doc", value: nil),
        MineToolItemModel(title: "帮助与客服", icon: "mine_system_customer_service", value: nil),
        MineToolItemModel(title: "安全中心", icon: "mine_system_safe_content", value: nil),
        MineToolItemModel(title: "红包奖励", icon: "mine_system_coupon", value: nil),
        MineToolItemModel(title: "认证招商", icon: "mine_system_v", value: nil),
        MineToolItemModel(title: "我的拍卖", icon: "mine_system_auction", value: nil),
        MineToolItemModel(title: "闲鱼family", icon: "mine_system_family", value: nil),
        MineToolItemModel(title: "鱼力行动", icon: "mine_system_action", value: nil),
    ]
    
    
    private func MineHeaderItemView(title: String, num: Int) -> some View {
        VStack(spacing: 5) {
            Text("\(num)")
                .fontWeight(.semibold)
            
            Text(title)
                .font(.system(size: 14))
        }
        .frame(maxWidth: .infinity)
    }
    
    private func MineHeaderView() -> some View {
        VStack {
            // 整体为上下结构，上半部分显示用户头像、昵称等信息
            // 下半部分显示收藏、历史记录等
            
            HStack {
                
                // 头像
                AsyncImage(url: URL(string: initVM.initModel?.user_info?.avatar ?? "")) { image in
                    image.resizable()
                        .clipShape(
                            Circle()
                        )
                } placeholder: {
                    ProgressView()
                }
                .frame(width: 60, height: 60)
                
                VStack(alignment: .leading) {
                    // 昵称
                    Text(initVM.initModel?.user_info?.nick_name ?? "")
                        .font(.system(size: 30, weight: .semibold))
                    
                    // 账号
                    Text("德玛*******西亚")
                        .font(.system(size: 14))
                        .foregroundColor(.black.opacity(0.5))
                }
                
                Spacer()
                
                Image(systemName: "chevron.right")
                    .font(.system(size: 12, weight: .bold))
                    .foregroundColor(.black.opacity(0.2))
                
                
            }
            
            HStack {
                MineHeaderItemView(title: "收藏", num: 0)
                MineHeaderItemView(title: "历史记录", num: 10)
                MineHeaderItemView(title: "关注", num: 30)
                MineHeaderItemView(title: "粉丝", num: 5)
            }
            .padding(.vertical, 10)
            
            Divider()
                .foregroundColor(Color(hex: 0xF6F6F6))
                .frame(height: 1)
            
        }
    }
    
    private func MineUserToolListView() -> some View {
        ForEach(mineUserTools) { mineUserSection in
            VStack(alignment: .leading) {
                Text(mineUserSection.title ?? "")
                    .font(.system(size: 20, weight: .semibold))
                    .padding(.vertical, 10)
                    .padding(.horizontal, 16)
                
                MineToolSectionView(mineToolItemModels: mineUserSection.itemList ?? [])
            }
        }
    }
    
    private func MineSystemToolListView() -> some View {
        MineToolSectionView(mineToolItemModels: mineSystemTools)
    }
    
    private func MineToolSectionView(mineToolItemModels: [MineToolItemModel]) -> some View {
        
        LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 4)) {
            ForEach(mineToolItemModels) { mineToolItemModel in
                
                VStack {
                    Image(mineToolItemModel.icon!)
                        .resize(size: CGSize(width: 30, height: 30), contentModel: .fit)
                    
                    HStack {
                        Text(mineToolItemModel.title ?? "")
                        if mineToolItemModel.value != nil {
                            Text("\(mineToolItemModel.value!)")
                        }
                    }
                    .font(.system(size: 12))
                }
            }
        }
        
        
    }
    
    
    private func MineNavView() -> some View {
        HStack {
            Spacer()
            
            Text(initVM.initModel?.user_info?.nick_name ?? "")
                .font(.system(size: 18, weight: .semibold))
                .foregroundColor(.black.opacity(navViewAlpha))
            Spacer()
            
            Button {
                withAnimation {
                    customTabbarVM.atFront = false
                    customTabbarVM.isAcvite.toggle()
                }
            } label: {
                Image("mine_setting")
                    .resize(size: CGSize(width: 20, height: 20), contentModel: .fit)
            }

            NavigationLink(destination: SettingView(), isActive: $customTabbarVM.isAcvite) {
                
            }
        }
        .padding(.horizontal, 16)
        //        .padding(.vertical, 5)
        .padding(.top, SCREEN_SAFE_INSETS.top + 5)
        .padding(.bottom, 5)
        .background(Color.white.opacity(navViewAlpha))
    }
    var body: some View {
        
        NavigationView {
            ScrollView {
                VStack(spacing: 0) {
                    // 本期视频到此结束，“我的”界面UI大致就是这样，下期视频将对页面数据与数据库进行同步，敬请期待，再见。
                    // 在所有内容的上方还有一片区域，该区域固定停留在顶部，当ScrollView向上滚动的过程中，该区域背景色从透明逐渐变成白色，并显示用户昵称
                    
                    // 接下来就需要让MineNavView在滚动过程中，保持固定在顶部
                    MineNavView()
                    // 修改层级
                        .zIndex(1)
                        .offset(y: scrollViewOffsetY)
                    // 想要让ScrollView能够滚动上去，需要内容足以撑满屏幕
                    
                    // MineHeaderView
                    MineHeaderView()
                        .padding(.horizontal, 16)
                        .overlay {
                            // 给MineHeaderView添加一个透明色的遮盖，并通过GeometryReader获取frame，这样就可以计算scrollView的偏移了
                            GeometryReader { proxy -> AnyView in
                                let frame = proxy.frame(in: .global)
                                let minY = frame.minY
                                let height = frame.height

                                DispatchQueue.main.async {
                                    if headerViewMinY == 0 {
                                        headerViewMinY = minY
                                    }

                                    scrollViewOffsetY = headerViewMinY - minY - SCREEN_SAFE_INSETS.top
                                    navViewAlpha = scrollViewOffsetY / height
                                }

                                return AnyView(
                                    Color.clear
                                )
                            }
                        }

                    Color.white
                        .frame(height: 20)
//
                    // MineUserToolListView
                    MineUserToolListView()

                    // userToolListView与systemToolListView之间的分割线
                    Rectangle()
                        .fill(Color(hex: 0xFAF9F9))
                        .frame(height: 10)

                    // MineSystemToolListView
                    MineSystemToolListView()

                    // 在滚动视图底部再添加一个MineHeaderView，方便后续获取偏移控制navView的背景透明度
                    MineHeaderView()
                        .opacity(0)

                    // 还需要一个用来表示TabbarView高度的view
                    Rectangle()
                        .fill(Color.white)
                        .frame(height: 80 + SCREEN_SAFE_INSETS.top + SCREEN_SAFE_INSETS.top)
                        .opacity(0)
                }
            }
            .navigationTitle("")
            .navigationBarHidden(true)
            .ignoresSafeArea(.all, edges: .top)
        }
        
        .navigationViewStyle(.stack)
        
    }
}

struct MineView_Previews: PreviewProvider {
    static var previews: some View {
        MineView()
    }
}
